package com.kumi.shop.product.service.impl;

import com.kumi.common.constant.ProductConstant;
import com.kumi.common.to.es.SkuEsModel;
import com.kumi.common.to.SkuHasStockVo;
import com.kumi.common.to.SkuReductionTo;
import com.kumi.common.to.SpuBoundTo;
import com.kumi.common.utils.R;
import com.kumi.shop.product.bean.*;
import com.kumi.shop.product.bean.Attr;
import com.kumi.shop.product.feign.CouponFeignService;
import com.kumi.shop.product.feign.SearchFeignService;
import com.kumi.shop.product.feign.WareFeiginService;
import com.kumi.shop.product.vo.*;
import com.kumi.shop.product.service.*;
import com.kumi.shop.product.vo.BaseAttrs;
import com.kumi.shop.product.vo.Images;
import com.kumi.shop.product.vo.Skus;
import com.kumi.shop.product.vo.SpuSaveVo;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.math.BigDecimal;
import java.util.*;
import java.util.stream.Collectors;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kumi.common.utils.PageUtils;
import com.kumi.common.utils.Query;

import com.kumi.shop.product.mapper.SpuInfoMapper;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.StringUtils;


@Service("spuInfoService")
public class SpuInfoServiceImpl extends ServiceImpl<SpuInfoMapper, SpuInfo> implements SpuInfoService {

    @Autowired
    private SpuInfoDescService spuInfoDescService;

    @Autowired
    private SpuImagesService imagesService;

    @Autowired
    private AttrService attrService;

    @Autowired
    private ProductAttrValueService productAttrValueService;

    @Autowired
    private SkuInfoService skuInfoService;

    @Autowired
    private SkuImagesService skuImagesService;

    @Autowired
    private SkuSaleAttrValueService skuSaleAttrValueService;

    @Autowired
    private CouponFeignService couponFeignService;

    @Autowired
    private BrandService brandService;

    @Autowired
    private CategoryService categoryService;

    @Autowired
    private WareFeiginService wareFeiginService;

    @Autowired
    private SearchFeignService searchFeignService;

    @Override
    public PageUtils queryPage(Map<String, Object> params) {
        IPage<SpuInfo> page = this.page(
                new Query<SpuInfo>().getPage(params),
                new QueryWrapper<SpuInfo>()
        );

        return new PageUtils(page);
    }

    /**
     * //TODO 高级部分完善
     * @param vo
     */
    @Transactional
    @Override
    public void saveSpuInfo(SpuSaveVo vo) {
        SpuInfo spuInfo = new SpuInfo();
        BeanUtils.copyProperties(vo,spuInfo);
        spuInfo.setCreateTime(new Date());
        spuInfo.setUpdateTime(new Date());
        this.saveBaseSpuInfo(spuInfo);

        List<String> decript = vo.getDecript();
        SpuInfoDesc spuInfoDesc = new SpuInfoDesc();
        spuInfoDesc.setSpuId(spuInfo.getId());
        spuInfoDesc.setDecript(String.join(",",decript));
        spuInfoDescService.saveSpInfoDecript(spuInfoDesc);

        List<String> images = vo.getImages();
        imagesService.saveImages(spuInfo.getId(),images);

        List<BaseAttrs> baseAttrs = vo.getBaseAttrs();
        List<ProductAttrValue> collect = baseAttrs.stream().map(attr -> {
            ProductAttrValue productAttrValue = new ProductAttrValue();
            productAttrValue.setAttrId(attr.getAttrId());
            Attr attr1 = attrService.getById(attr.getAttrId());
            productAttrValue.setAttrName(attr1.getAttrName());
            productAttrValue.setAttrValue(attr.getAttrValues());
            productAttrValue.setQuickShow(attr.getShowDesc());
            productAttrValue.setSpuId(spuInfo.getId());
            return productAttrValue;
        }).collect(Collectors.toList());
        productAttrValueService.saveProductAttr(collect);

        Bounds bounds = vo.getBounds();
        SpuBoundTo spuBoundTo = new SpuBoundTo();
        BeanUtils.copyProperties(bounds,spuBoundTo);
        spuBoundTo.setSpuId(spuInfo.getId());
        R r1 = couponFeignService.saveSpuBouds(spuBoundTo);
        if (r1.getCode() != 0){
            log.error("保存失败");
        }

        List<Skus> skus = vo.getSkus();
        if (skus != null || skus.size() > 0){
            skus.forEach(item -> {
                String defaultimg = "";
                for (Images img : item.getImages()) {
                    if (img.getDefaultImg() == 1){
                        defaultimg = img.getImgUrl();
                    }
                }
                SkuInfo skuInfo = new SkuInfo();
                BeanUtils.copyProperties(item,skuInfo);
                skuInfo.setBrandId(spuInfo.getBrandId());
                skuInfo.setCatalogId(spuInfo.getCatalogId());
                skuInfo.setSaleCount(0L);
                skuInfo.setSpuId(spuInfo.getId());
                skuInfo.setSkuDefaultImg(defaultimg);
                skuInfoService.saveSkuInfo(skuInfo);

                Long skuId = skuInfo.getSkuId();
                List<SkuImages> imagesList = item.getImages().stream().map(img -> {
                    SkuImages skuImages = new SkuImages();
                    skuImages.setSkuId(skuId);
                    skuImages.setImgUrl(img.getImgUrl());
                    skuImages.setDefaultImg(img.getDefaultImg());
                    return skuImages;
                }).filter(entiry -> {
                    return !StringUtils.isEmpty(entiry.getImgUrl());
                }).collect(Collectors.toList());
                // TODO 没有图片路径的无需保存
                skuImagesService.saveBatch(imagesList);

                List<AttrVos> attr = item.getAttr();
                List<SkuSaleAttrValue> attrValues = attr.stream().map(a -> {
                    SkuSaleAttrValue attrValue = new SkuSaleAttrValue();
                    BeanUtils.copyProperties(a, attrValue);
                    attrValue.setSkuId(skuId);
                    return attrValue;
                }).collect(Collectors.toList());
                skuSaleAttrValueService.saveBatch(attrValues);
                SkuReductionTo skuReductionTo = new SkuReductionTo();
                BeanUtils.copyProperties(item,skuReductionTo);
                skuReductionTo.setSkuId(skuId);
                if (skuReductionTo.getFullCount() > 0 || skuReductionTo.getFullPrice().compareTo(new BigDecimal("0")) == 1){
                    R r = couponFeignService.saveSkuReduction(skuReductionTo);
                    if (r.getCode() != 0){
                        log.error("远程保存spu优惠信息失败");
                    }
                }
            });
        }


    }

    @Override
    public void saveBaseSpuInfo(SpuInfo spuInfo) {
        this.baseMapper.insert(spuInfo);
    }

    @Override
    public void saveSpInfoDecript(SpuInfoDesc spuInfoDesc) {

    }

    @Override
    public PageUtils queryPageByCondition(Map<String, Object> params) {
        QueryWrapper<SpuInfo> wrapper = new QueryWrapper<>();
        String key = (String) params.get("key");
        String status = (String) params.get("status");
        String brandId = (String) params.get("brandId");
        String catelogId = (String) params.get("catelogId");
        if (!StringUtils.isEmpty(key)){
            wrapper.and((w) -> {
                w.eq("id",key).or().like("spu_name",key);
            });
        }
        if (!StringUtils.isEmpty(status)){
            wrapper.eq("publish_status",status);
        }
        if (!StringUtils.isEmpty(brandId) && !"0".equalsIgnoreCase(brandId)){
            wrapper.eq("brand_id",brandId);
        }
        if (!StringUtils.isEmpty(catelogId) && !"0".equalsIgnoreCase(catelogId)){
            wrapper.eq("catalog_id  ",catelogId);
        }
        IPage<SpuInfo> page = this.page(
                new Query<SpuInfo>().getPage(params),
                wrapper
        );

        return new PageUtils(page);
    }

    @Override
    public void up(Long spuId) {
        List<SkuInfo> skuInfos = skuInfoService.getSkusByspuId(spuId);

        List<Long> collect = skuInfos.stream().map(SkuInfo::getSkuId).collect(Collectors.toList());

        List<ProductAttrValue> listforspu = productAttrValueService.listforspu(spuId);
        List<Long> attrIds = listforspu.stream().map(attr -> {
            return attr.getAttrId();
        }).collect(Collectors.toList());

        List<Long> searchAttrs = attrService.selectSearchAttrs(attrIds);
        Set<Long> idSet = new HashSet<>(searchAttrs);

        List<SkuEsModel.Attrs> list = listforspu.stream().filter(item -> {
            return idSet.contains(item.getAttrId());
        }).map(item -> {
            SkuEsModel.Attrs attrs1 = new SkuEsModel.Attrs();
            BeanUtils.copyProperties(item, attrs1);
            return attrs1;
        }).collect(Collectors.toList());

        //TODO 发送远程调用 库存系统查询是否有库存 //TODO 发送远程调用 库存系统查询是否有库存
        Map<Long, Boolean> map = new HashMap<>();
        try {
            List<SkuHasStockVo> skuHasStock = wareFeiginService.getSkuHasStock(collect);
            for (SkuHasStockVo skuHasStockVo : skuHasStock) {
                map.put(skuHasStockVo.getSkuId(),skuHasStockVo.getHasStock());
            }
        } catch (Exception e) {
            log.error("库存查询异常{}",e);
        }
        Map<Long, Boolean> finalMap = map;
        List<SkuEsModel> upProduct = skuInfos.stream().map(sku -> {
            SkuEsModel model = new SkuEsModel();
            BeanUtils.copyProperties(sku,model);
            model.setSkuPrice(sku.getPrice());
            model.setSkuImg(sku.getSkuDefaultImg());

            if (finalMap == null){
                model.setHasStock(true);
            }else {
                model.setHasStock(finalMap.get(sku.getSkuId()));
            }

            //TODO 热度评分
            model.setHotScore(0L);
            //TODO 查询品牌和分类的信息
            Brand brand = brandService.getById(model.getBrandId());
            model.setBrandName(brand.getName());
            model.setBrandImg(brand.getLogo());
            Category category = categoryService.getById(model.getCatalogId());
            model.setCatalogName(category.getName());
            model.setAttrs(list);


            return model;
        }).collect(Collectors.toList());

        //TODO 将数据发给es进行保存
        R r = searchFeignService.productStatusUp(upProduct);
        if (r.getCode() == 0){
            baseMapper.updateSpuStatus(spuId, ProductConstant.StatusEnum.SPU_UP.getCode());
        }else {
            //TODO 接口幂等性

        }
    }
}